using System;

namespace NEnsure
{
	public class BrokenRule
	{
		private readonly string _propertyName;
		private readonly object _propertyValue;
		private readonly IBusinessRule _rule;
		private string _errorMessage;

		public string PropertyName
		{
			get { return _propertyName; }
		}

		public object PropertyValue
		{
			get { return _propertyValue; }
		}

		public IBusinessRule Rule
		{
			get { return _rule; }
		}

		public string ErrorMessage
		{
			get { return _errorMessage; }
		}

		public BrokenRule(string propertyName, object propertyValue, IBusinessRule rule)
		{
			if (string.IsNullOrEmpty(propertyName))
			{
				throw new ArgumentNullException("propertyName");
			}

			if (rule == null)
			{
				throw new ArgumentNullException("rule");
			}

			_propertyName = propertyName;
			_propertyValue = propertyValue;
			_rule = rule;

			buildErrorMessage();
		}

		public override string ToString()
		{
			return string.Format("Property '{0}' with value '{1}' broke rule '{2}.'", _propertyName, _propertyValue, _rule.RuleKey);
		}

		private void buildErrorMessage()
		{
			if (!string.IsNullOrEmpty(_rule.ErrorFormat))
			{
				_errorMessage = _rule.ErrorFormat.Replace("{key}", "{0}").Replace("{value}", "{1}");
				_errorMessage = string.Format(_errorMessage, _propertyName, _propertyValue);
			}

			if (_errorMessage == null)
			{
				_errorMessage = string.Empty;
			}
		}
	}
}
